import type { Router, RouteRecordNormalized, RouteRecordRaw } from 'vue-router'

/**
 * 路由调试工具 - 提供各种格式的路由打印方法
 */
export const routeDebugger = {
  /**
   * 打印所有路由的详细信息
   * @param router Vue Router实例
   * @param title 可选的标题
   */
  printAllRoutes(router: Router, title = '所有路由信息'): void {
    console.log(`%c ---------- ${title} ----------`, 'background:#67C23A; color:white; padding: 4px; border-radius: 4px;');
    
    const allRoutes = router.getRoutes();
    
    // 获取组件名称的辅助函数
    const getComponentInfo = (component: any): string => {
      if (!component) return 'null';
      
      if (typeof component === 'function') {
        const fnStr = component.toString();
        if (fnStr.includes('import(')) {
          const matches = fnStr.match(/import\(['"](.+?)['"][\)]?/);
          return matches ? `动态导入: ${matches[1]}` : '动态导入组件';
        }
        return '函数组件';
      }
      
      if (component.name) {
        return `组件: ${component.name}`;
      }
      
      return '未命名组件';
    };
    
    // 打印路由信息的递归函数
    const printRoute = (route: RouteRecordNormalized, indent = ''): void => {
      // 处理路由组件信息
      let componentInfo: any = '无组件';
      
      if (route.components) {
        componentInfo = {};
        for (const [name, comp] of Object.entries(route.components)) {
          componentInfo[name] = getComponentInfo(comp);
        }
      }
      
      console.log(`${indent}${route.path} [${route.name ? String(route.name) : 'unnamed'}]`, {
        component: componentInfo,
        meta: route.meta || {}
      });
      
      // 递归处理子路由
      if (route.children && route.children.length > 0) {
        route.children.forEach(child => {
          // 使用类型断言处理子路由类型转换
          printRoute(child as RouteRecordNormalized, indent + '  ');
        });
      }
    };
    
    // 遍历并打印所有路由
    allRoutes.forEach(route => {
      printRoute(route);
    });
    
    console.log(`共计 ${allRoutes.length} 个路由`);
  },
  
  /**
   * 打印路由的树形结构
   * @param router Vue Router实例
   */
  printRouteTree(router: Router): void {
    console.log('%c ---------- 路由树结构 ----------', 'background:#409EFF; color:white; padding: 4px; border-radius: 4px;');
    
    const routes = router.getRoutes();
    // 按路径排序
    routes.sort((a, b) => a.path.localeCompare(b.path));
    
    // 构建路由树
    const routeTree: Record<string, any> = {};
    
    routes.forEach(route => {
      const segments = route.path.split('/').filter(Boolean);
      let current = routeTree;
      
      if (segments.length === 0) {
        // 根路由
        current['root'] = {
          name: route.name,
          meta: route.meta
        };
      } else {
        // 嵌套路由
        segments.forEach((segment, index) => {
          if (!current[segment]) {
            current[segment] = {};
          }
          
          current = current[segment];
          
          if (index === segments.length - 1) {
            current['__route__'] = {
              name: route.name,
              meta: route.meta
            };
          }
        });
      }
    });
    
    // 递归打印树
    const printTree = (node: any, prefix = ''): void => {
      for (const key in node) {
        if (key === '__route__') {
          continue;
        }
        
        const routeInfo = node[key].__route__;
        const routeName = routeInfo ? ` [${routeInfo.name ? String(routeInfo.name) : 'unnamed'}]` : '';
        
        console.log(`${prefix}${key}${routeName}`);
        
        // 打印子节点
        printTree(node[key], prefix + '  ');
      }
    };
    
    printTree(routeTree);
  },
  
  /**
   * 打印动态路由组件信息
   * @param router Vue Router实例
   */
  printDynamicRoutes(router: Router): void {
    console.log('%c ---------- 动态路由组件信息 ----------', 'background:#E6A23C; color:white; padding: 4px; border-radius: 4px;');
    
    const routes = router.getRoutes();
    const dynamicRoutes = routes.filter(route => {
      // 检查components是否包含动态导入的组件
      if (!route.components) return false;
      
      return Object.values(route.components).some(comp => {
        if (typeof comp !== 'function') return false;
        return comp.toString().includes('import(');
      });
    });
    
    dynamicRoutes.forEach(route => {
      console.log(`%c${route.path} [${route.name ? String(route.name) : 'unnamed'}]`, 'font-weight: bold; color: #409EFF;');
      
      if (route.components) {
        for (const [name, comp] of Object.entries(route.components)) {
          if (typeof comp === 'function' && comp.toString().includes('import(')) {
            const matches = comp.toString().match(/import\(['"](.+?)['"][\)]?/);
            const componentPath = matches ? matches[1] : '未知路径';
            console.log(`  -> ${name}: ${componentPath}`);
          }
        }
      }
      
      // 打印元数据
      if (Object.keys(route.meta || {}).length > 0) {
        console.log('  Meta:', route.meta);
      }
    });
    
    console.log(`共发现 ${dynamicRoutes.length} 个动态路由`);
  },
  
  /**
   * 查找特定名称或路径的路由
   * @param router Vue Router实例
   * @param search 要搜索的名称或路径
   */
  findRoute(router: Router, search: string): void {
    console.log(`%c ---------- 搜索路由: ${search} ----------`, 'background:#F56C6C; color:white; padding: 4px; border-radius: 4px;');
    
    const routes = router.getRoutes();
    const results = routes.filter(route => {
      return (
        (route.name && String(route.name).includes(search)) || 
        route.path.includes(search)
      );
    });
    
    if (results.length === 0) {
      console.log('没有找到匹配的路由');
      return;
    }
    
    results.forEach(route => {
      console.log(`%c${route.path} [${route.name ? String(route.name) : 'unnamed'}]`, 'font-weight: bold; color: #409EFF;');
      
      // 打印组件信息
      if (route.components) {
        console.log('  组件:');
        for (const [name, comp] of Object.entries(route.components)) {
          if (typeof comp === 'function') {
            const str = comp.toString();
            if (str.includes('import(')) {
              const matches = str.match(/import\(['"](.+?)['"][\)]?/);
              console.log(`    -> ${name}: ${matches ? matches[1] : '动态导入组件'}`);
            } else {
              console.log(`    -> ${name}: 函数组件`);
            }
          } else if (comp && comp.name) {
            console.log(`    -> ${name}: ${comp.name}`);
          } else {
            console.log(`    -> ${name}: 未知组件`);
          }
        }
      }
      
      // 打印元数据
      if (Object.keys(route.meta || {}).length > 0) {
        console.log('  Meta:', route.meta);
      }
    });
    
    console.log(`共找到 ${results.length} 个匹配的路由`);
  },

  /**
   * 统计并检查路由信息
   * @param router Vue Router实例
   * @param expectedRoutes 预期应该存在的路由路径数组 (可选)
   */
  analyzeRoutes(router: Router, expectedRoutes?: string[]): void {
    console.log('%c ---------- 路由统计分析 ----------', 'background:#409EFF; color:white; padding: 4px; border-radius: 4px;');
    
    const allRoutes = router.getRoutes();
    
    // 按类型统计路由
    const staticRoutes = allRoutes.filter(route => {
      // 静态路由通常是直接导入的组件，而非动态导入
      if (!route.components) return false;
      
      return Object.values(route.components).some(comp => {
        if (typeof comp !== 'function') return true; // 非函数组件视为静态
        return !comp.toString().includes('import('); // 不包含动态导入
      });
    });
    
    const dynamicRoutes = allRoutes.filter(route => {
      // 动态路由通常使用动态导入
      if (!route.components) return false;
      
      return Object.values(route.components).some(comp => {
        if (typeof comp !== 'function') return false;
        return comp.toString().includes('import(');
      });
    });
    
    // 其他路由 (可能没有组件的路由，如重定向)
    const otherRoutes = allRoutes.filter(route => {
      return !staticRoutes.includes(route) && !dynamicRoutes.includes(route);
    });
    
    // 打印统计信息
    console.log('路由统计:');
    console.log(`  总路由数: ${allRoutes.length}`);
    console.log(`  静态路由: ${staticRoutes.length}`);
    console.log(`  动态路由: ${dynamicRoutes.length}`);
    console.log(`  其他路由: ${otherRoutes.length}`);
    
    // 检查是否有预期路由未注册
    if (expectedRoutes && expectedRoutes.length > 0) {
      console.log('%c ---------- 路由完整性检查 ----------', 'background:#F56C6C; color:white; padding: 4px; border-radius: 4px;');
      
      const allRoutePaths = allRoutes.map(r => r.path);
      const missingRoutes = expectedRoutes.filter(path => !allRoutePaths.includes(path));
      
      if (missingRoutes.length > 0) {
        console.log('%c以下路由未注册:', 'color: #F56C6C; font-weight: bold;');
        missingRoutes.forEach(path => {
          console.log(`  - ${path}`);
        });
      } else {
        console.log('%c所有预期路由已注册', 'color: #67C23A; font-weight: bold;');
      }
    }
    
    // 检查系统路由是否完整
    this.checkSystemRoutes(router);
  },
  
  /**
   * 检查系统相关路由是否完整
   * @param router Vue Router实例
   */
  checkSystemRoutes(router: Router): void {
    console.log('%c ---------- 系统路由检查 ----------', 'background:#E6A23C; color:white; padding: 4px; border-radius: 4px;');
    
    // 系统管理相关的预期路由
    const expectedSystemRoutes = [
      '/system/user',
      '/system/role',
      '/system/menu',
      '/system/permission',
      '/system/log/operlog',
      '/system/log/loginlog',
      '/system/config',
      '/system/storage'
    ];
    
    // 获取实际路由路径
    const actualRoutes = router.getRoutes().map(r => r.path);
    
    // 对于正确配置的路由，路径中通常以/dashboard开头，需要检查两种形式
    const dashboardPaths = expectedSystemRoutes.map(r => `/dashboard${r}`);
    
    // 检查每条预期路由
    console.log('系统路由检查结果:');
    
    expectedSystemRoutes.forEach(route => {
      // 检查是否存在路由(普通形式或dashboard前缀形式)
      const exists = actualRoutes.includes(route) || actualRoutes.includes(`/dashboard${route}`);
      
      // 尝试查找包含该路径片段的路由
      const similar = actualRoutes.filter(r => r.includes(route.replace(/^\//, '')));
      
      if (exists) {
        console.log(`%c✅ ${route}`, 'color: #67C23A;');
      } else if (similar.length > 0) {
        console.log(`%c⚠️ ${route} (未找到完全匹配，但有类似路径: ${similar.join(', ')})`, 'color: #E6A23C;');
      } else {
        console.log(`%c❌ ${route} (未注册)`, 'color: #F56C6C;');
      }
    });
    
    // 特别关注operlog路由
    const operLogPath = '/system/log/operlog';
    const loginLogPath = '/system/log/loginlog';
    
    const operLogExists = actualRoutes.some(r => r.includes('operlog'));
    const loginLogExists = actualRoutes.some(r => r.includes('loginlog'));
    
    console.log('%c ---------- 日志路由详细分析 ----------', 'background:#E6A23C; color:white; padding: 4px; border-radius: 4px;');
    console.log(`操作日志路由状态: ${operLogExists ? '✅ 已注册' : '❌ 未注册'}`);
    console.log(`登录日志路由状态: ${loginLogExists ? '✅ 已注册' : '❌ 未注册'}`);
    
    // 提供修复建议
    if (!operLogExists && loginLogExists) {
      console.log('%c修复建议:', 'font-weight: bold;');
      console.log('检查后端返回的菜单数据中是否包含操作日志菜单项');
      console.log('可临时手动注册操作日志路由: router.addRoute("AppLayout", { path: "/system/log/operlog", name: "operlog", component: () => import("@/views/system/log/operlog/index.vue"), meta: { requiresAuth: true, title: "操作日志" } })');
    }
  },

  /**
   * 分别计算和打印动态路由和静态路由
   * @param router Vue Router实例
   */
  countRoutesByType(router: Router): void {
    console.log('%c ---------- 按类型统计路由 ----------', 'background:#409EFF; color:white; padding: 4px; border-radius: 4px;');
    
    const allRoutes = router.getRoutes();
    
    // 识别动态路由 (使用动态导入的路由)
    const dynamicRoutes = allRoutes.filter(route => {
      if (!route.components) return false;
      
      return Object.values(route.components).some(comp => {
        if (typeof comp !== 'function') return false;
        return comp.toString().includes('import(');
      });
    });
    
    // 识别静态路由 (直接导入组件的路由)
    const staticRoutes = allRoutes.filter(route => {
      if (!route.components) return false;
      
      return Object.values(route.components).some(comp => {
        if (typeof comp !== 'function') return true; // 非函数组件视为静态
        return !comp.toString().includes('import('); // 不包含动态导入的函数组件
      });
    });
    
    // 其他类型路由 (可能是重定向或没有组件的路由)
    const otherRoutes = allRoutes.filter(route => {
      return !dynamicRoutes.includes(route) && !staticRoutes.includes(route);
    });
    
    // 1. 首先打印统计信息
    console.log('%c路由总数统计:', 'font-weight: bold;');
    console.log(`  总路由数: ${allRoutes.length}`);
    console.log(`  动态路由: ${dynamicRoutes.length}`);
    console.log(`  静态路由: ${staticRoutes.length}`);
    console.log(`  其他路由: ${otherRoutes.length}`);
    console.log('');
    
    // 2. 打印动态路由详细信息
    console.log('%c ---------- 动态路由详细信息 (共 ' + dynamicRoutes.length + ' 个) ----------', 'background:#67C23A; color:white; padding: 4px; border-radius: 4px;');
    dynamicRoutes.forEach((route, index) => {
      console.log(`%c${index + 1}. ${route.path} [${route.name ? String(route.name) : 'unnamed'}]`, 'color: #409EFF; font-weight: bold;');
      
      // 打印组件信息
      if (route.components) {
        for (const [name, comp] of Object.entries(route.components)) {
          if (typeof comp === 'function' && comp.toString().includes('import(')) {
            const matches = comp.toString().match(/import\(['"](.+?)['"][\)]?/);
            const componentPath = matches ? matches[1] : '未知路径';
            console.log(`   组件: ${name} => ${componentPath}`);
          }
        }
      }
      
      // 打印元数据
      if (Object.keys(route.meta || {}).length > 0) {
        console.log('   Meta:', route.meta);
      }
    });
    console.log('');
    
    // 3. 打印静态路由详细信息
    console.log('%c ---------- 静态路由详细信息 (共 ' + staticRoutes.length + ' 个) ----------', 'background:#E6A23C; color:white; padding: 4px; border-radius: 4px;');
    staticRoutes.forEach((route, index) => {
      console.log(`%c${index + 1}. ${route.path} [${route.name ? String(route.name) : 'unnamed'}]`, 'color: #409EFF; font-weight: bold;');
      
      // 打印组件信息
      if (route.components) {
        for (const [name, comp] of Object.entries(route.components)) {
          let componentInfo = '未知组件';
          if (typeof comp === 'function') {
            componentInfo = '函数组件 (非动态导入)';
          } else if (comp && comp.name) {
            componentInfo = `命名组件: ${comp.name}`;
          }
          console.log(`   组件: ${name} => ${componentInfo}`);
        }
      }
      
      // 打印元数据
      if (Object.keys(route.meta || {}).length > 0) {
        console.log('   Meta:', route.meta);
      }
    });
    
    // 4. 如果有需要，可以打印其他类型路由
    if (otherRoutes.length > 0) {
      console.log('');
      console.log('%c ---------- 其他路由 (共 ' + otherRoutes.length + ' 个) ----------', 'background:#F56C6C; color:white; padding: 4px; border-radius: 4px;');
      otherRoutes.forEach((route, index) => {
        console.log(`%c${index + 1}. ${route.path} [${route.name ? String(route.name) : 'unnamed'}]`, 'color: #409EFF;');
        
        if (route.redirect) {
          console.log(`   重定向到: ${route.redirect}`);
        }
        
        // 打印元数据
        if (Object.keys(route.meta || {}).length > 0) {
          console.log('   Meta:', route.meta);
        }
      });
    }
  },

  /**
   * 简单打印动态路由和静态路由的个数
   * @param router Vue Router实例
   */
  printRouteCounts(router: Router): void {
    const allRoutes = router.getRoutes();
    
    // 识别动态路由 (使用动态导入的路由)
    const dynamicRoutes = allRoutes.filter(route => {
      if (!route.components) return false;
      
      return Object.values(route.components).some(comp => {
        if (typeof comp !== 'function') return false;
        return comp.toString().includes('import(');
      });
    });
    
    // 识别静态路由 (直接导入组件的路由)
    const staticRoutes = allRoutes.filter(route => {
      if (!route.components) return false;
      
      return Object.values(route.components).some(comp => {
        if (typeof comp !== 'function') return true; // 非函数组件视为静态
        return !comp.toString().includes('import('); // 不包含动态导入的函数组件
      });
    });
    
    // 直接按照要求的格式打印
    console.log('动态路由个数:', dynamicRoutes.length, '静态路由个数:', staticRoutes.length);
  },
  
  /**
   * 检查路由组件映射表与实际路由注册情况的差异
   * 找出存在于组件映射表但未在路由器中注册的路由
   * @param router Vue Router实例
   */
  findMissingRoutes(router: Router): void {
    console.log('%c ---------- 路由注册差异分析 ----------', 'background:#F56C6C; color:white; padding: 4px; border-radius: 4px;');
    
    const allRoutes = router.getRoutes();
    const allRoutePaths = allRoutes.map(r => r.path);
    const allRouteNames = allRoutes.map(r => r.name ? String(r.name) : '');
    
    // 获取当前应用可用的视图组件
    const modules = import.meta.glob('../../views/**/*.vue');
    const componentModules = import.meta.glob('../../components/**/*.vue');
    
    // 获取router/modules目录下的动态路由模块
    try {
      // 直接检查system/log/operlog路由是否存在
      const operlogRouteExists = allRoutePaths.some(path => 
        path.includes('operlog') || path.includes('system/log/operlog')
      );
      
      console.log(`%c操作日志路由检查:`, 'font-weight: bold;');
      
      if (operlogRouteExists) {
        const operlogRoute = allRoutes.find(r => 
          r.path.includes('operlog') || r.path.includes('system/log/operlog')
        );
        console.log(`  ✅ 已注册: ${operlogRoute?.path} [${operlogRoute?.name ? String(operlogRoute.name) : 'unnamed'}]`);
      } else {
        console.log(`  ❌ 未注册: 操作日志路由(/system/log/operlog 或 /system/operlog)未注册`);
        console.log(`  📋 检查确认操作日志组件存在: ${modules['../../views/system/log/operlog/index.vue'] ? '✓ 存在' : '✗ 不存在'}`);
      }
      
      // 检查路由名称是否存在但路径不同
      const operlogNameExists = allRouteNames.some(name => 
        name.includes('operlog') || name === '操作日志'
      );
      
      if (operlogNameExists && !operlogRouteExists) {
        const routeWithOperlogName = allRoutes.find(r => 
          r.name && (String(r.name).includes('operlog') || String(r.name) === '操作日志')
        );
        console.log(`  ⚠️ 发现名称包含operlog的路由但路径异常: ${routeWithOperlogName?.path} [${routeWithOperlogName?.name ? String(routeWithOperlogName.name) : 'unnamed'}]`);
      }
    } catch (error) {
      console.error('路由差异分析出错:', error);
    }
    
    // 计算预期的路由数量
    const expectedSystemRoutes = [
      '/system/user',
      '/system/role',
      '/system/menu',
      '/system/permission',
      '/system/log/operlog',
      '/system/log/loginlog',
      '/system/config',
      '/system/storage'
    ];
    
    // 对比预期和实际路由数量
    console.log('%c路由数量差异分析:', 'font-weight: bold;');
    const registeredSystemRoutes = allRoutePaths.filter(path => 
      path.includes('/system/')
    );
    
    console.log(`  预期系统路由: ${expectedSystemRoutes.length} 个`);
    console.log(`  实际系统路由: ${registeredSystemRoutes.length} 个`);
    
    if (expectedSystemRoutes.length !== registeredSystemRoutes.length) {
      console.log(`  ⚠️ 系统路由数量不匹配，差异: ${expectedSystemRoutes.length - registeredSystemRoutes.length}`);
    }
    
    // 对比预期的动态路由总数和实际数量
    const expectedDynamicRouteCount = 31; // 根据您提供的动态路由列表，应该是31个
    const dynamicRoutes = allRoutes.filter(route => {
      if (!route.components) return false;
      
      return Object.values(route.components).some(comp => {
        if (typeof comp !== 'function') return false;
        return comp.toString().includes('import(');
      });
    });
    
    console.log(`  预期动态路由: ${expectedDynamicRouteCount} 个`);
    console.log(`  实际动态路由: ${dynamicRoutes.length} 个`);
    
    if (expectedDynamicRouteCount !== dynamicRoutes.length) {
      console.log(`  ⚠️ 动态路由数量不匹配，差异: ${expectedDynamicRouteCount - dynamicRoutes.length}`);
      
      // 查看是否多了一个路由
      if (dynamicRoutes.length > expectedDynamicRouteCount) {
        console.log(`  🔍 检测到多余路由，这可能导致计数错误。正在分析...`);
        
        // 打印所有动态路由名称，帮助查找重复或意外的路由
        console.log('  动态路由列表:');
        dynamicRoutes.forEach((route, index) => {
          console.log(`    ${index}: ${route.path} [${route.name ? String(route.name) : 'unnamed'}]`);
        });
      }
    }
    
    // 提供可能的问题原因和解决方案
    console.log('%c可能的问题原因:', 'font-weight: bold;');
    console.log('  1. 后端返回的菜单数据中缺少操作日志菜单项');
    console.log('  2. 路由加载过程中出现重复路由注册');
    console.log('  3. 路由组件映射表和实际注册的路由存在不一致');
    
    console.log('%c建议解决方案:', 'font-weight: bold;');
    console.log('  1. 使用addMissingOperLogRoute()手动添加操作日志路由');
    console.log('  2. 检查后端返回的菜单数据是否包含操作日志');
    console.log('  3. 检查是否在多个地方重复注册了同一路由');
  }
};

// 将调试器挂载到window上以便控制台访问
if (typeof window !== 'undefined') {
  // @ts-ignore
  window.routeDebugger = routeDebugger;
}

export default routeDebugger; 